<template>
  <div class="layout-padding" >
    <div class="layout-padding-auto layout-padding-view" style="overflow: scroll!important;">
			<el-row shadow="hover" v-show="showSearch" class="ml10">
				<el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
					<el-form-item label="模板名称" prop="name">
						<el-input placeholder="请输入模板名称" v-model="state.queryForm.name" />
					</el-form-item>
					<el-form-item>
						<el-button icon="search" type="primary" @click="getDataList">
							查询
						</el-button>
						<el-button icon="Refresh" @click="resetQuery">重置</el-button>
					</el-form-item>
				</el-form>
			</el-row>
      <!-- 操作按钮区域 -->
      <el-row>
        
        <div class="mb8" style="width: 100%">
          <el-button 
            plain
						icon="folder-add"
            type="primary" 
            class="ml10" 
            @click="openDrawer('')"
            v-auth="'aiDocumentTemplate_add'"
          >
            新增
          </el-button>
          <el-button 
            plain 
            :disabled="multiple" 
            icon="Delete" 
            type="primary"
            v-auth="'aiDocumentTemplate_del'" 
            @click="handleDelete(selectObjs)"
          >
            删除
          </el-button>
          <right-toolbar 
            v-model:showSearch="showSearch" 
            :export="'aiDocumentTemplate_export'"
            @exportExcel="exportExcel" 
            class="ml10 mr20" 
            style="float: right;"
            @queryTable="getDataList"
          />
        </div>
      </el-row>

      <!-- 数据表格区域 -->
			<!-- 卡片网格区域 -->
			<div class="w-full">

				<!-- 加载骨架屏 -->
				<el-skeleton v-if="state.loading" :rows="4" animated />

				<!-- 空状态 -->
				<el-empty
					v-else-if="!state.dataList || state.dataList.length === 0"
					description="暂无模板，点击『新增』创建一个吧"
					class="py-10"
				/>

				<!-- 卡片网格 -->
				<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-4 items-start">
					<div 
						v-for="item in state.dataList" 
						:key="item.id" 
						class="flex flex-col p-3.5 border border-gray-200 dark:border-gray-700 rounded-xl bg-white dark:bg-gray-800 shadow-sm hover:shadow-lg hover:-translate-y-0.5 transition-all duration-150 ease-in-out min-h-95"
					>
						<div class="flex items-center gap-2 mb-2.5 flex-shrink-0">
							<div 
								class="flex-1 font-semibold truncate cursor-pointer text-gray-900 dark:text-gray-100" 
								:title="item.name"
							>
								{{ item.name || '未命名模板' }}
							</div>
						</div>

						<div 
							class="relative flex-1 border border-gray-200 dark:border-gray-600 rounded-lg overflow-hidden bg-white dark:bg-gray-700 cursor-pointer group min-h-0"
							@click="openWritingDrawer(item)"
						>
							<div class="absolute inset-0 bg-transparent group-hover:bg-black/5 dark:group-hover:bg-white/5 transition-colors duration-150 z-10"></div>
							<div class="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-150 z-20">
								<div class="bg-blue-600 text-white px-4 py-2 rounded-lg text-sm font-medium shadow-lg">
									<el-icon class="mr-1"><Edit /></el-icon>
									点击开始写作
								</div>
							</div>
							<SafeSandboxIframe
								:html="item.content"
								minHeight="200px"
								maxHeight="none"
								class="h-full"
							/>
						</div>

						<div class="flex justify-start items-center pt-3 mt-4 border-t border-gray-100 dark:border-gray-700">
							<el-button
								class="!p-2 text-gray-600 rounded-full transition-colors dark:text-gray-300 hover:text-primary hover:bg-gray-100 dark:hover:bg-gray-700"
								text
								type="primary"
								v-auth="'aiDocumentTemplate_edit'"
								@click="openWritingDrawer(item)"
								:title="'开始写作'"
							>
								<el-icon><EditPen /></el-icon>
							</el-button>

							<el-button
								class="!p-2 text-gray-600 rounded-full transition-colors dark:text-gray-300 hover:text-primary hover:bg-gray-100 dark:hover:bg-gray-700"
								text
								type="primary"
								v-auth="'aiDocumentTemplate_edit'"
								@click="openDrawer(item.id)"
								:title="'编辑模板'"
							>
								<el-icon><Edit /></el-icon>
							</el-button>

							<el-button
								class="!p-2 text-gray-600 rounded-full transition-colors dark:text-gray-300 hover:text-primary hover:bg-gray-100 dark:hover:bg-gray-700"
								text
								type="primary"
								v-auth="'aiDocumentTemplate_del'"
								@click="handleDelete([item.id])"
								:title="'删除模板'"
							>
								<el-icon><Delete /></el-icon>
							</el-button>

							<div class="flex-grow"></div>
							<div class="flex items-center text-xs text-gray-500 dark:text-gray-400">
								<el-icon class="mr-1"><Clock /></el-icon>
								{{ parseDate(item.createTime) }}
							</div>
							<el-checkbox
								class="ml-4"
								:value="isSelected(item.id)"
								@change="() => toggleSelect(item.id)"
							></el-checkbox>
						</div>
					</div>
				</div>
			</div>


      <!-- 分页组件 -->
      <pagination 
        @size-change="sizeChangeHandle" 
        @current-change="currentChangeHandle" 
        v-bind="state.pagination" 
        class="mt-3"
      />
    </div>

    <!-- 编辑、新增弹窗 -->
    <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />

    <!-- 导入excel弹窗 (需要在 upms-biz/resources/file 下维护模板) -->
    <upload-excel
      ref="excelUploadRef"
      title="导入"
      url="/knowledge/aiDocumentTemplate/import"
      temp-url="/admin/sys-file/local/file/aiDocumentTemplate.xlsx"
      @refreshDataList="getDataList"
    />

		<!-- 公文模板设计器抽屉 -->
		<TemplateDrawer ref="templateDrawerRef" @refresh="getDataList" />

		<!-- 公文写作抽屉 -->
		<WritingDrawer 
		   ref="writingDrawerRef"
			:template="currentTemplate"
		/>

  </div>
</template>

<script setup lang="ts" name="systemAiDocumentTemplate">
// ========== 导入声明 ==========
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs } from "/@/api/knowledge/aiWritter";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { parseDate } from '/@/utils/formatTime';
import { defineAsyncComponent } from 'vue';
import TemplateDrawer from './template-drawer.vue'
import WritingDrawer from './writing-drawer.vue'
import SafeSandboxIframe from '/@/components/SafeSandboxIframe/index.vue'
import { Edit, Delete, Clock, EditPen } from '@element-plus/icons-vue'

// ========== 组件声明 ==========
// 异步加载表单弹窗组件
const FormDialog = defineAsyncComponent(() => import('./template-form.vue'));

// ========== 组件引用 ==========
const formDialogRef = ref();          // 表单弹窗引用
const excelUploadRef = ref();         // Excel上传弹窗引用
const queryRef = ref();               // 查询表单引用
const templateDrawerRef = ref();

// ========== 响应式数据 ==========
const showSearch = ref(true);         // 是否显示搜索区域
const selectObjs = ref([]) as any;    // 表格多选数据
const multiple = ref(true);           // 是否多选
const writingDrawerRef = ref(); // 公文写作抽屉显示状态
const currentTemplate = ref<any>(null); // 当前选中的模板

// ========== 表格状态 ==========
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    name: '',
  },    // 查询参数
  pageList: fetchList // 分页查询方法
});

// ========== Hook引用 ==========
// 表格相关Hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state);

// ========== 方法定义 ==========
/**
 * 重置查询条件
 */
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields();
  // 清空多选
  selectObjs.value = [];
  // 重新查询
  getDataList();
};

/**
 * 导出Excel文件
 */
const exportExcel = () => {
  downBlobFile(
    '/knowledge/aiDocumentTemplate/export',
    Object.assign(state.queryForm, { ids: selectObjs }),
    'aiDocumentTemplate.xlsx'
  );
};

/**
 * 删除数据处理
 * @param ids 要删除的数据ID数组
 */
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};

const openDrawer = (id: string) => {
  templateDrawerRef.value?.openDrawer(id);
}

/**
 * 打开公文写作抽屉
 * @param template 模板数据
 */
const openWritingDrawer = (template: any) => {
  currentTemplate.value = template;
  writingDrawerRef.value.openWritingDrawer(template);
};

// ---- 卡片选择：替代表格多选 ----
const selectedSet = ref<Set<string>>(new Set());

const isSelected = (id: string) => selectedSet.value.has(id);

const toggleSelect = (id: string) => {
  if (selectedSet.value.has(id)) {
    selectedSet.value.delete(id);
  } else {
    selectedSet.value.add(id);
  }
  // 同步到你原有的多选状态
  selectObjs.value = Array.from(selectedSet.value);
  multiple.value = selectObjs.value.length === 0;
};

</script>
